package org.linlinjava.litemall.core.service;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.linlinjava.litemall.core.dto.GoodsAllinone;
import org.linlinjava.litemall.core.util.LitemallGoodsUtil;
import org.linlinjava.litemall.core.vo.CatVo;
import org.linlinjava.litemall.core.qcode.QCodeService;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.linlinjava.litemall.core.util.AdminResponseCode.GOODS_NAME_EXIST;

@Slf4j
@Service
public class AdminGoodsService {

    @Autowired
    private LitemallGoodsService goodsService;
    @Autowired
    private LitemallGoodsSpecificationService specificationService;
    @Autowired
    private LitemallGoodsAttributeService attributeService;
    @Autowired
    private LitemallGoodsProductService productService;
    @Autowired
    private LitemallCategoryService categoryService;
    @Autowired
    private LitemallBrandService brandService;

    @Autowired
    private VendorGoodsTagService goodsTagService;

    @Autowired
    private QCodeService qCodeService;
    @Autowired
    private LitemallCartService cartService;

    public Object list(Long vendorId,
                       String goodsSn,
                       String name,
                       Integer page,
                       Integer limit,
                       String sort,
                       String order) {
        List<LitemallGoods> goodsList = goodsService.querySelective(vendorId, goodsSn, name, page, limit, sort, order);
        return ResponseUtil.okList(goodsList);
    }

    private Object validate(GoodsAllinone goodsAllinone) {
        LitemallGoods goods = goodsAllinone.getGoods();
        String name = goods.getName();
        if (StringUtils.isEmpty(name)) {
            return ResponseUtil.badArgument();
        }

        // 品牌商可以不设置，如果设置则需要验证品牌商存在
        Long brandId = goods.getBrandId();
        if (brandId != null && brandId != 0) {
            if (brandService.findById(brandId) == null) {
                return ResponseUtil.badArgumentValue("品牌信息错误!");
            }
        }
        // 分类可以不设置，如果设置则需要验证分类存在
        Long categoryId = goods.getCategoryId();
        if (categoryId != null && categoryId != 0) {
            if (categoryService.findById(categoryId) == null) {
                return ResponseUtil.badArgumentValue("分类信息错误!");
            }
        }

        LitemallGoodsSpecification[] specifications = goodsAllinone.getSpecifications();
        for (LitemallGoodsSpecification specification : specifications) {
            String spec = specification.getSpecification();
            if (StringUtils.isEmpty(spec)) {
                return ResponseUtil.badArgumentValue("规格信息错误!");
            }
            String value = specification.getValue();
            if (StringUtils.isEmpty(value)) {
                return ResponseUtil.badArgumentValue("规格值不能为空!");
            }
        }

        LitemallGoodsProduct[] products = goodsAllinone.getProducts();
        for (LitemallGoodsProduct product : products) {
            Integer number = product.getNumber();
            if (number == null || number < 0) {
                return ResponseUtil.badArgumentValue("库存不能为空!");
            }

            BigDecimal price = product.getPrice();
            if (price == null) {
                return ResponseUtil.badArgumentValue("价格不能为空!");
            }

            String[] productSpecifications = product.getSpecifications();
            if (productSpecifications.length == 0) {
                return ResponseUtil.badArgumentValue();
            }
        }

        return null;
    }

    /**
     * 编辑商品
     * <p>
     * TODO
     * 目前商品修改的逻辑是
     * 1. 更新litemall_goods表
     * 2. 逻辑删除litemall_goods_specification、litemall_goods_attribute、litemall_goods_product
     * 3. 添加litemall_goods_specification、litemall_goods_attribute、litemall_goods_product
     * <p>
     * 这里商品三个表的数据采用删除再添加的策略是因为
     * 商品编辑页面，支持管理员添加删除商品规格、添加删除商品属性，因此这里仅仅更新是不可能的，
     * 只能删除三个表旧的数据，然后添加新的数据。
     * 但是这里又会引入新的问题，就是存在订单商品货品ID指向了失效的商品货品表。
     * 因此这里会拒绝管理员编辑商品，如果订单或购物车中存在商品。
     * 所以这里可能需要重新设计。
     */
    @Transactional
    public Object update(GoodsAllinone goodsAllinone) {
        LitemallGoods goods = goodsAllinone.getGoods();

        LitemallGoodsSpecification[] specifications = goodsAllinone.getSpecifications();
        specifications = null == specifications || specifications.length == 0 ? LitemallGoodsUtil.initSpecification(goods) : specifications;
        goodsAllinone.setSpecifications(specifications);

        LitemallGoodsProduct[] products = goodsAllinone.getProducts();
        products = null == products || products.length == 0 ? LitemallGoodsUtil.initGoodsProduct(goods) : products;
        if(products.length == 1){
            products[0].setPrice(goods.getRetailPrice());
            products[0].setNumber(goods.getNumber());
        }

        goodsAllinone.setProducts(products);

        Object error = validate(goodsAllinone);
        if (error != null) {
            return error;
        }

        LitemallGoodsAttribute[] attributes = goodsAllinone.getAttributes();

        VendorTag[] tags = goodsAllinone.getTags();

        Long goodsId = goods.getId();

        // 将生成的分享图片地址写入数据库
        String url = qCodeService.createGoodShareImage(goodsId.toString(), goods.getPicUrl(), goods.getName());
        goods.setShareUrl(url);

        // 商品基本信息表litemall_goods
        if (goodsService.updateById(goods) == 0) {
            throw new RuntimeException("更新数据失败");
        }

        // 商品规格表litemall_goods_specification
        for (LitemallGoodsSpecification specification : specifications) {
            specification.setGoodsId(goodsId);
            // 目前只支持更新规格表的图片字段
            if (specification.getUpdateTime() == null) {
                specificationService.updateById(specification);
            } else {
                specificationService.add(specification);
            }
        }

        // 商品货品表litemall_product
        for (LitemallGoodsProduct product : products) {
            product.setGoodsId(goodsId);
            if (product.getUpdateTime() == null) {
                productService.updateById(product);
            } else {
                productService.add(product);
            }
        }

        // 商品参数表litemall_goods_attribute
        if(null != attributes) {
            for (LitemallGoodsAttribute attribute : attributes) {
                if (attribute.getId() == null || attribute.getId() == 0) {
                    attribute.setGoodsId(goodsId);
                    attributeService.add(attribute);
                } else if (attribute.getDeleted()) {
                    attributeService.deleteById(attribute.getId());
                } else if (attribute.getUpdateTime() == null) {
                    attributeService.updateById(attribute);
                }
            }
        }

        // 这里需要注意的是购物车litemall_cart有些字段是拷贝商品的一些字段，因此需要及时更新
        // 目前这些字段是goods_sn, goods_name, price, pic_url
        for (LitemallGoodsProduct product : products) {
            cartService.updateProduct(product.getId(), goods.getGoodsSn(), goods.getName(), product.getPrice(), product.getUrl());
        }

        // 商品标签
        if(null != tags) {
            for (VendorTag tag : tags) {
                VendorGoodsTag gt = new VendorGoodsTag();
                gt.setGoodsId(goodsId);
                gt.setTagId(tag.getId());
                gt.setTagName(tag.getName());
                goodsTagService.add(gt);
            }
        }

        return ResponseUtil.ok();
    }

    @Transactional
    public Object delete(LitemallGoods goods) {
        Long goodsId = goods.getId();
        if (goodsId == null) {
            return ResponseUtil.badArgument();
        }

        goodsService.deleteById(goodsId);
        specificationService.deleteByGid(goodsId);
        attributeService.deleteByGid(goodsId);
        productService.deleteByGid(goodsId);
        return ResponseUtil.ok();
    }

    @Transactional
    public Object create(GoodsAllinone goodsAllinone) {
        LitemallGoods goods = goodsAllinone.getGoods();

        LitemallGoodsSpecification[] specifications = goodsAllinone.getSpecifications();
        specifications = null == specifications || specifications.length == 0 ? LitemallGoodsUtil.initSpecification(goods) : specifications;
        goodsAllinone.setSpecifications(specifications);

        LitemallGoodsProduct[] products = goodsAllinone.getProducts();
        products = null == products || products.length == 0 ? LitemallGoodsUtil.initGoodsProduct(goods) : products;
        goodsAllinone.setProducts(products);

        Object error = validate(goodsAllinone);
        if (error != null) {
            return error;
        }

        String name = goods.getName();
        if (goodsService.checkExistByName(name)) {
            return ResponseUtil.fail(GOODS_NAME_EXIST, "商品名已经存在");
        }

        // 商品基本信息表litemall_goods
        goodsService.add(goods);

        //将生成的分享图片地址写入数据库
        String url = qCodeService.createGoodShareImage(goods.getId().toString(), goods.getPicUrl(), goods.getName());
        if (!StringUtils.isEmpty(url)) {
            goods.setShareUrl(url);
            if (goodsService.updateById(goods) == 0) {
                throw new RuntimeException("更新数据失败");
            }
        }

        // 商品规格表litemall_goods_specification
        for (LitemallGoodsSpecification specification : specifications) {
            specification.setGoodsId(goods.getId());
            specificationService.add(specification);
        }

        // 商品参数表litemall_goods_attribute
        LitemallGoodsAttribute[] attributes = goodsAllinone.getAttributes();
        if(null != attributes) {
            for (LitemallGoodsAttribute attribute : attributes) {
                attribute.setGoodsId(goods.getId());
                attributeService.add(attribute);
            }
        }

        // 商品货品表litemall_product
        for (LitemallGoodsProduct product : products) {
            product.setGoodsId(goods.getId());
            productService.add(product);
        }

        // 商品标签
        VendorTag[] tags = goodsAllinone.getTags();
        if (null != tags) {
            for (VendorTag tag : tags) {
                VendorGoodsTag gt = new VendorGoodsTag();
                gt.setGoodsId(goods.getId());
                gt.setTagId(tag.getId());
                gt.setTagName(tag.getName());
                goodsTagService.add(gt);
            }
        }

        return ResponseUtil.ok();
    }

    public Object list2() {
        // http://element-cn.eleme.io/#/zh-CN/component/cascader
        // 管理员设置“所属分类”
        List<LitemallCategory> l1CatList = categoryService.queryL1();
        List<CatVo> categoryList = new ArrayList<>(l1CatList.size());

        for (LitemallCategory l1 : l1CatList) {
            CatVo l1CatVo = new CatVo();
            l1CatVo.setValue(l1.getId());
            l1CatVo.setLabel(l1.getName());

            List<LitemallCategory> l2CatList = categoryService.queryByPid(l1.getId());
            List<CatVo> children = new ArrayList<>(l2CatList.size());
            for (LitemallCategory l2 : l2CatList) {
                CatVo l2CatVo = new CatVo();
                l2CatVo.setValue(l2.getId());
                l2CatVo.setLabel(l2.getName());
                children.add(l2CatVo);
            }
            l1CatVo.setChildren(children);

            categoryList.add(l1CatVo);
        }

        // http://element-cn.eleme.io/#/zh-CN/component/select
        // 管理员设置“所属品牌商”
        List<LitemallBrand> list = brandService.all();
        List<Map<String, Object>> brandList = new ArrayList<>(l1CatList.size());
        for (LitemallBrand brand : list) {
            Map<String, Object> b = new HashMap<>(2);
            b.put("value", brand.getId());
            b.put("label", brand.getName());
            brandList.add(b);
        }

        Map<String, Object> data = new HashMap<>();
        data.put("categoryList", categoryList);
        data.put("brandList", brandList);
        return ResponseUtil.ok(data);
    }

    public Object detail(Long id) {
        LitemallGoods goods = goodsService.findById(id);
        List<LitemallGoodsProduct> products = productService.queryByGid(id);
        List<LitemallGoodsSpecification> specifications = specificationService.queryByGid(id);
        List<LitemallGoodsAttribute> attributes = attributeService.queryByGid(id);
        List<VendorGoodsTag> goodsTags = goodsTagService.queryByGoodsId(id);

        Long categoryId = goods.getCategoryId();
        LitemallCategory category = categoryService.findById(categoryId);
        Long[] categoryIds = new Long[]{};
        if (category != null) {
            Long parentCategoryId = category.getPid();
            categoryIds = new Long[]{parentCategoryId, categoryId};
        }

        List<Long> tagIds = new ArrayList<>();
        for(VendorGoodsTag gt : goodsTags) {
            tagIds.add(gt.getTagId());
        }

        Map<String, Object> data = new HashMap<>();
        data.put("goods", goods);
        data.put("specifications", specifications);
        data.put("products", products);
        data.put("attributes", attributes);
        data.put("categoryIds", categoryIds);
        data.put("tags", tagIds.toArray());

        return ResponseUtil.ok(data);
    }

    public Object getGoodsTags(Long id) {
        List<VendorGoodsTag> goodsTags = goodsTagService.queryByGoodsId(id);
        List<VendorTag> tags = new ArrayList<>();
        for(VendorGoodsTag goodsTag : goodsTags) {
            VendorTag tag = new VendorTag();
            tag.setName(goodsTag.getTagName());
            tag.setId(goodsTag.getTagId());
            tags.add(tag);
        }
        return ResponseUtil.ok(tags);
    }

    public Object listByTag(Long tagId, Integer page, Integer limit) {
        List<VendorGoodsTag> goodsTags = goodsTagService.queryByTagId(tagId, page, limit);
        List<Long> ids = new ArrayList<>();
        for(VendorGoodsTag gt : goodsTags) {
            ids.add(gt.getGoodsId());
        }
        List<LitemallGoods> goodsList = goodsService.queryByIds((Long[]) ids.toArray());
        return ResponseUtil.okList(goodsList);
    }
}

